package edu.aynu.controller;

import edu.aynu.entity.Problem;
import edu.aynu.service.ProblemService;
import edu.aynu.util.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import javax.annotation.Resource;

/**
 * (Problem)表控制层
 *
 * @author sitong
 * @date 2021-06-21 20:24:21
 */
@RestController
public class ProblemController {
    /**
     * 服务对象
     */
    @Resource
    private ProblemService problemService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("problem")
    public Result selectOne(Integer id) {
        Problem problem = this.problemService.queryById(id);
        if (problem == null) {
            return Result.fail();
        }
        return Result.success().add("problem", problem);
    }

    /**
     * 通过实体作为筛选条件查询
     */
    @GetMapping("problems")
    public Result queryAll(Problem problem) {
        List<Problem> list = this.problemService.queryAll(problem);
        if (list.size() == 0) {
            return Result.fail();
        }
        return Result.success().add("problems", list);
    }

    /**
     * 新增数据
     */
    @PostMapping("problem")
    public Result insert(@RequestBody Problem problem) {
        int i = this.problemService.insert(problem);
        if (i == 0) {
            return Result.fail().add("msg", "该题目已存在");
        }
        return Result.success();
    }

    /**
     * 修改数据
     */
    @PutMapping("problem")
    public Result update(Problem problem) {
        int i = this.problemService.update(problem);
        if (i == 0) {
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * 通过主键删除数据
     *
     * @return 是否成功
     */
    @DeleteMapping("problem")
    public Result deleteById(Integer id) {
        boolean b = this.problemService.deleteById(id);
        if (b == false) {
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * 通过Es查询数据
     * @param title
     * @return
     */
    @GetMapping("problem/es")
    public Result selectByEs(String title) {
        List<Problem> problems = problemService.queryByEs(title);
        if(problems.size() == 0) {
            return Result.fail();
        }
        return Result.success().add("problems", problems);
    }
}
